package 二叉树;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution637 {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);
        TreeNode treeNode1 = new TreeNode(2);
        TreeNode treeNode2 = new TreeNode(3);
        treeNode.left = treeNode1;
        treeNode.right = treeNode2;
        System.out.println(averageOfLevels(treeNode));
    }

    public static List<Double> averageOfLevels(TreeNode root) {
        List<List<Double>> resultList = new ArrayList<>();
        List<Double> result = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Double> list = new ArrayList<>();
            while (size > 0) {
                TreeNode poll = queue.poll();
                if (poll != null) {
                    list.add((double) poll.val);
                    if (poll.left != null) {
                        queue.offer(poll.left);
                    }
                    if (poll.right != null) {
                        queue.offer(poll.right);
                    }
                }

                size--;
            }
            resultList.add(list);
        }
        //遍历求平均值
        for (int i = 0; i < resultList.size(); i++) {
            List<Double> doubles = resultList.get(i);
            double all = 0.00000;
            double avg = 0.00000;
            int size = doubles.size();
            for (int j = 0; j < size; j++) {
                Double aDouble = doubles.get(j);
                all = (all + aDouble);
            }
            avg = all / size;
            result.add(avg);
        }
        return result;
    }
}
